package weaver.aiyh_pcn.convert_pdf;

import aiyh.utils.Util;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import org.apache.axiom.util.base64.Base64Utils;
import org.apache.commons.io.IOUtils;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.seconddev.CreateDocForJSGJXT;
import weaver.file.ImageFileManager;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.FileProcessor;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/11/15 0015 14:38
 * PDF 合并action
 */


public class ConvertPdfAction implements Action {

//	需要合并的字段
	private String mergeField;
//	合并后存放文件的字段
	private String mergeToField;
//	1.流程字段，2，action参数，3流程字段+action参数,4 流程多字段拼接
	private String mergePDFNameType;
//	action参数的文件名
	private String mergePDFName;
//	流程字段和多字段
	private String mergePDFNameFields;


	@Override
	public String execute(RequestInfo requestInfo) {
		ToolUtil toolUtil = new ToolUtil();
		toolUtil.writeDebuggerLog("进入PDF转换action！");
		User user = requestInfo.getRequestManager().getUser();
		String billTableName = requestInfo.getRequestManager().getBillTableName();
		String requestId = requestInfo.getRequestid();
		String workflowId = requestInfo.getWorkflowid();
		if(StringUtils.isNullOrEmpty(mergeField)){
			return Action.SUCCESS;
		}
		if(StringUtils.isNullOrEmpty(mergeToField)){
//			TODO 修改labelId
			requestInfo.getRequestManager().setMessagecontent(Util.getHtmlLabelName(-88650,user.getLanguage(),"没有配置合并后PDF存放字段，请联系管理员！"));
			requestInfo.getRequestManager().setMessageid("1");
			return Action.FAILURE_AND_CONTINUE;
		}
//		获取流程数据
		RecordSet rs = new RecordSet();
		String query = "select * from " + billTableName + " where requestid = ?";
		rs.executeQuery(query,requestId);
		Map<String, Object> workflowData = Util.recordSet2Map(rs);
		toolUtil.writeDebuggerLog("流程数据：" + workflowData);
		if(workflowData == null){
			toolUtil.writeErrorLog("未查询到流程数据：" + query + " --> " + requestId);
			return Action.SUCCESS;
		}
//		获取文件id
		String docIds = Util.null2String(workflowData.get(mergeField));
		toolUtil.writeDebuggerLog("文件id：" + docIds);
		if(StringUtils.isNullOrEmpty(docIds)){
			return Action.SUCCESS;
		}

//		查询字段的目录
		String docCategorys = Util.getDocCategorys(workflowId, mergeField);
		CreateDocForJSGJXT createDocForJSGJXT = new CreateDocForJSGJXT();
		String[] docCategoryArray = docCategorys.split(",");
		int docCategory = 0;
		if(docCategoryArray.length == 3){
			docCategory = Integer.parseInt(docCategoryArray[2]);
		}else{
			for (String s : docCategoryArray) {
				docCategory = Integer.parseInt(s);
			}
		}
		String fileName = "";
		String defaultFileName = "合同水印合并文件";
		if("1".equals(mergePDFNameType)){
//			1.流程字段，2，action参数，3流程字段+action参数,4 流程多字段拼接
			String fields = Util.null2String(workflowData.get(mergePDFNameFields));
			String[] fieldArr = fields.split(",");
			fileName = Util.null2DefaultStr(workflowData.get(fieldArr[0]),defaultFileName);
		}else if("2".equals(mergePDFNameType)){
//			1.流程字段，2，action参数，3流程字段+action参数,4 流程多字段拼接
			fileName = mergePDFName;
		}else if("3".equals(mergePDFNameType)){
//			1.流程字段，2，action参数，3流程字段+action参数,4 流程多字段拼接
			fileName = Util.null2DefaultStr(workflowData.get(mergePDFNameFields),defaultFileName) + mergePDFName;
		}else if("4".equals(mergePDFNameType)){
//			1.流程字段，2，action参数，3流程字段+action参数,4 流程多字段拼接
			String fields = Util.null2String(workflowData.get(mergePDFNameFields));
			String[] fieldArr = fields.split(",");
			for (String field : fieldArr) {
				fileName += Util.null2String(workflowData.get(field));
			}
		}
		if(StringUtils.isNullOrEmpty(fileName)){
			fileName = defaultFileName;
		}
		toolUtil.writeDebuggerLog("合并文件参数：fileName：" +  fileName + "  docCategory：" + docCategory + "  docIds：" + docIds);
		int fileId;
		if(docIds.split(",").length <= 1){
//			查询真实文件id
			query = "select imagefileid from docimagefile where docid = ?";
			toolUtil.writeDebuggerLog(query + " --->  " + docIds);
			rs.executeQuery(query,docIds);
			rs.next();
			fileId = Util.getIntValue(rs.getString("imagefileid"),0);
			FileProcessor fileProcessor = new FileProcessor();
			InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId);
			byte[] bytes = new byte[0];
			try {
				bytes = IOUtils.toByteArray(inputStreamById);
			} catch (IOException e) {
				e.printStackTrace();
				toolUtil.writeErrorLog("复制文件时，文件转为base64出错，文件转换出错！" + e);
			}
			String base64 = Base64Utils.encode(bytes);
			fileId = fileProcessor.Process("base64:" + base64, docCategorys, user, fileName + ".pdf");
			if(fileId <= 0){
				toolUtil.writeErrorLog(docCategorys + "---------->" + fileName);
				toolUtil.writeDebuggerLog("文件创建错误、错误id：" + fileId);
				toolUtil.writeErrorLog(base64);
//			TODO 修改labelId
				requestInfo.getRequestManager().setMessagecontent(Util.getHtmlLabelName(-88651,user.getLanguage(),"合并pdf错误，请联系管理员！"));
				requestInfo.getRequestManager().setMessageid("1");
				return Action.FAILURE_AND_CONTINUE;
			}
		}else{
			fileId = createDocForJSGJXT.creatDoc(user, fileName, docCategory, docIds);
		}

		if(fileId <= 0){
			toolUtil.writeDebuggerLog("文件合并错误！(-2:用户为空,-1:文档获取异常)、错误id：" + fileId);
//			TODO 修改labelId
			requestInfo.getRequestManager().setMessagecontent(Util.getHtmlLabelName(-88651,user.getLanguage(),"合并pdf错误，请联系管理员！"));
			requestInfo.getRequestManager().setMessageid("1");
			return Action.FAILURE_AND_CONTINUE;
		}
//		将合并的文件回写到流程中
		PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(billTableName, ParaMap.create().put(mergeToField, fileId),
				Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
		toolUtil.writeDebuggerLog("数据回写：" + sqlResult.getSqlStr() + " --> 参数： " + sqlResult.getArgs());
		rs.executeUpdate(sqlResult.getSqlStr(),sqlResult.getArgs());
		return Action.SUCCESS;
	}

	public String getMergeField() {
		return mergeField;
	}

	public void setMergeField(String mergeField) {
		this.mergeField = mergeField;
	}

	public String getMergeToField() {
		return mergeToField;
	}

	public void setMergeToField(String mergeToField) {
		this.mergeToField = mergeToField;
	}

	public String getMergePDFNameType() {
		return mergePDFNameType;
	}

	public void setMergePDFNameType(String mergePDFNameType) {
		this.mergePDFNameType = mergePDFNameType;
	}

	public String getMergePDFName() {
		return mergePDFName;
	}

	public void setMergePDFName(String mergePDFName) {
		this.mergePDFName = mergePDFName;
	}

	public String getMergePDFNameFields() {
		return mergePDFNameFields;
	}

	public void setMergePDFNameFields(String mergePDFNameFields) {
		this.mergePDFNameFields = mergePDFNameFields;
	}
}
